package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.config.WebSocketConfiguration;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: orderServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Author 龙培
 * @Create 2025/3/15 14:26
 * @Version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    WebSocketServer webSocketServer;
    /**
     * Description: 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断购物车和地址是否存在
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        ShoppingCart shoppingCart = new ShoppingCart();
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);
        //查询购物车数据
        List<ShoppingCart> carts = shoppingCartMapper.list(shoppingCart);
        if (carts == null || carts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(currentId);

        orderMapper.insert(orders);

        //向订单详情表插入数据
        List<OrderDetail> detailList = new ArrayList<>();
        for (ShoppingCart cart : carts) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(cart, detail);
            detail.setOrderId(orders.getId());
            detailList.add(detail);
        }
        orderDetailMapper.insertBatch(detailList);

        //清空购物车
        shoppingCartMapper.clean(currentId);
        //封装vo对象
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }

    @Override
    public PageResult PageQuery4Order(int page,int pageSize,Integer status) {
        //根据用户id以及订单状态查询订单
        Long currentId = BaseContext.getCurrentId();
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(currentId);
        ordersPageQueryDTO.setStatus(status);

        //分页查询
        PageHelper.startPage(page,pageSize);
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);

        //封装vo对象
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            List<OrderDetail> details = orderDetailMapper.listByOrderId(order.getId());
            orderVO.setOrderDetailList(details);
            orderVOList.add(orderVO);
        }
        return new PageResult(orders.getTotal(), orderVOList);
    }

    /**
     * Description: 根据订单id查询订单详情
     * @param orderId
     * @return
     */
    @Override
    public OrderVO getOrderDetailByOrderId(Long orderId) {
        Orders orders = orderMapper.getByOrderId(orderId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> details = orderDetailMapper.listByOrderId(orders.getId());
        orderVO.setOrderDetailList(details);
        return orderVO;
    }

    @Override
    public void cancelOrder(Long orderId) {
        Orders orders = orderMapper.getByOrderId(orderId);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        Integer status = orders.getStatus();
        if(status > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //退款
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //退款

            //此处省略退款逻辑........

            //设置订单支付状态为退款
            orders.setPayStatus(Orders.REFUND);
        }

        //更新订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orderMapper.update(orders);
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //回调给前端
        Map map = new HashMap();
        map.put("type", 1); //1表示支付成功，2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号"+outTradeNo);

        System.out.println("支付成功，回调给前端");
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public void repetitionOrder(Long orderId) {
        //根据订单id查询订单详情
        List<OrderDetail> detailList = orderDetailMapper.listByOrderId(orderId);
        List<ShoppingCart> cartList = new ArrayList<>();
        for (OrderDetail orderDetail : detailList) {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, cart);
            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());
            cart.setId(null);
            cartList.add(cart);
        }
        shoppingCartMapper.insertBatch(cartList);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            List<OrderDetail> details = orderDetailMapper.listByOrderId(order.getId());
            orderVO.setOrderDetailList(details);
            orderVOList.add(orderVO);
        }
        return new PageResult(orders.getTotal(), orderVOList);
    }

    @Override
    public OrderStatisticsVO statistics() {
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        Long currentId = BaseContext.getCurrentId();
        List<Orders> ordersList = orderMapper.getAllOrders();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Integer toBeConfirmed = 0; //待接单
        Integer confirmed = 0; //已接单即待派送
        Integer deliveryInProgress = 0; //派送中
        for (Orders orders : ordersList) {
            if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
                toBeConfirmed++;
            }else if(orders.getStatus().equals(Orders.CONFIRMED)){
                confirmed++;
            }else if(orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
                deliveryInProgress++;
            }
        }
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public void confirmOrder(Long id) {
        //* 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(id);
        orderMapper.update(orders);
    }

    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersConfirmDTO) {
        Orders orders = orderMapper.getByOrderId(ordersConfirmDTO.getId());
        if(orders == null){ //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){ //订单状态不是已接单
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(orders.getPayStatus().equals(Orders.PAID)) {
            //退款

            //此处省略退款逻辑........
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersConfirmDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void admincancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getByOrderId(ordersCancelDTO.getId());
        if(orders == null){ //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getPayStatus().equals(Orders.PAID)) {
            //退款

            //此处省略退款逻辑........
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void deliveryOrder(Long id) {
        Orders order = orderMapper.getByOrderId(id);
        if(order == null){ //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!order.getStatus().equals(Orders.CONFIRMED)){ //订单状态不是已接单(待派送)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    @Override
    public void completeOrder(Long id) {
        Orders order = orderMapper.getByOrderId(id);
        if (order == null|| !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }
}

